package com.toro.dao.Impl;

import com.toro.dao.GroupDao;
import com.toro.dao.UserDao;
import com.toro.domain.Group;
import com.toro.utils.JDBCUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * execute(String sql)
 *   **可以执行任何 SQL 语句，返回 boolean 值。**如果 sql 是一个 SELECT 语句（查询）则返回 true，
 * 可以通过 getResultSet() 获得结果集，如果 sql 是 DML 语句或者 DDL 语句（更新等）则返回 false。
 * 但它返回多个结果集，操作起来比较麻烦，效率也不够高。故一般使用 executeQuery、executeUpdate，而不使用 execute。
 *
 * executeQuery(String sql)
 *   **使用 SELECT 语句查询，返回单个结果集 ResultSet。**通过 next() 方法来遍历。
 *
 * executeUpdate(String sql)
 *   **用于执行 DDL 和 DML 语句，返回其影响的记录的条数（int）。
 * **对于 CREATE TABLE 或 DROP TABLE 等不对行进行操作的语句，executeUpdate 的返回值总为零。
 **/

/**
 * @ClassName: GroupDaoImpl
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/17 15:27
 */
@Slf4j
public class GroupDaoImpl implements GroupDao {
    UserDao userDao = new UserDaoImpl();

    /**
     * @Description: 获取群成员
     * @Param: [groupId]
     * @Return: java.util.ArrayList<java.lang.Integer>
     * @Author: ToroLHZ
     * @Date: 2023/12/24 14:54
     **/
    @Override
    public List<Integer> getAllMembers(int groupId) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Integer> members = new ArrayList<>();
        String sql = "select userid from t_group_user where groupid = ?";
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            ps.setInt(1, groupId);
//            log.debug("组装后的sql:{}", ps);
            rs = ps.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("userid");
                members.add(id);
            }
            return members;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(connection, ps, rs);
        }
        return null;
    }

    /**
     * @Description: 创建群
     * @Param: [groupName, creator, membersList]
     * @Return: java.lang.Boolean
     * @Author: ToroLHZ
     * @Date: 2023/12/24 14:27
     **/
    @Override
    public Boolean createGroup(String groupName, String creator, ArrayList<Integer> membersList) {
        Connection connection = null;
        PreparedStatement ps = null;
        boolean flag = true;
        try {
            int id = userDao.getUserIdByUsername(creator);
            String sql = "INSERT INTO t_group (name,creator) VALUES (?,?)";
            //1、获取连接(获取链接的JDBCUtils工具代码在后面已经给出)
            connection = JDBCUtils.getConnection();
            //2、预编译sql语句
            ps = connection.prepareStatement(sql);
            ps.setObject(1, groupName);
            ps.setObject(2, id);
//            log.debug("组装后的sql:{}", ps.toString());
            //4、执行操作
            ps.executeUpdate();
            int groupId = getGroupIdByGroupName(groupName);
            for (Integer userId : membersList) {
                boolean b = joinGroup(groupId, userId);
                if (!b) {
                    flag = false;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5、资源关闭（具体工具类代码在后面已经给出）
            JDBCUtils.closeResource(connection, ps);
        }
        return flag;
    }

    /**
     * @Description: 加入群
     * @Param: [groupId, userId]
     * @Return: boolean
     * @Author: ToroLHZ
     * @Date: 2023/12/24 14:53
     **/
    @Override
    public boolean joinGroup(int groupId, int userId) {
        Connection connection = null;
        PreparedStatement ps = null;
        boolean flag = false;
        try {
            String sql = "INSERT INTO t_group_user (userid,groupid) VALUES (?,?)";
            //1、获取连接(获取链接的JDBCUtils工具代码在后面已经给出)
            connection = JDBCUtils.getConnection();
            //2、预编译sql语句
            ps = connection.prepareStatement(sql);
            ps.setObject(1, userId);
            ps.setObject(2, groupId);
//            log.debug("加入群 组装后的sql:{}", ps.toString());
            //4、执行操作
            ps.executeUpdate();
            flag = true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5、资源关闭（具体工具类代码在后面已经给出）
            JDBCUtils.closeResource(connection, ps);
        }
        return flag;
    }

    /**
     * @Description: 获取群id
     * @Param: [groupName]
     * @Return: int
     * @Author: ToroLHZ
     * @Date: 2023/12/24 14:53
     **/
    @Override
    public int getGroupIdByGroupName(String groupName) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select id from t_group where name = ?";
        int id = 0;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            ps.setString(1, groupName);
//            log.debug("组装后的sql:{}", ps);
            rs = ps.executeQuery();
            if (rs.next()) {
                id = rs.getInt("id");
            } else {
                id = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(connection, ps, rs);
        }
        return id;
    }

    /**
     * @Description: 通过群名称获取群数据
     * @Param: [groupName]
     * @Return: Group
     * @Author: ToroLHZ
     * @Date: 2023/12/24 15:03
     **/
    @Override
    public Group getGroupByGroupName(String groupName) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select id,name,creator from t_group where name = ?";
        Group group = null;
        try {
            group = new Group();
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            ps.setString(1, groupName);
//            log.debug("组装后的sql:{}", ps);
            rs = ps.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("id");
                group.setGroupId(id);
                String name = rs.getString("name");
                group.setGroupName(name);
                int creator = rs.getInt("creator");
                group.setCreatorId(creator);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(connection, ps, rs);
        }
        return group;
    }

    /**
     * @Description: 获取成员id, 判断用户是否在群内
     * @Param: [groupId, userId]
     * @Return: Group
     * @Author: ToroLHZ
     * @Date: 2023/12/26 18:59
     **/
    @Override
    public boolean InGroupByGroupIdUserId(int groupId, int userId) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select count(*) from t_group_user where userid = ? and groupid = ?";
        boolean flag = false;
        try {
            Group group = new Group();
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            ps.setInt(1, userId);
            ps.setInt(2, groupId);
//            log.debug("组装后的sql:{}", ps);
            rs = ps.executeQuery();
            if (rs.next()) {
                int count = rs.getInt(1);
                if (count > 0) {
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(connection, ps, rs);
        }
        return flag;
    }

    /**
     * @Description: 删除数据通过id
     * @Param: [userId, groupId]
     * @Return: void
     * @Author: ToroLHZ
     * @Date: 2023/12/26 19:45
     **/
    @Override
    public void deleteUserById(int userId, int groupId) {
        System.out.println("sql语句");
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "delete from t_group_user where userid = ? and groupid = ?";
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            ps.setInt(1, userId);
            ps.setInt(2, groupId);
//            log.debug("组装后的sql:{}", ps);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(connection, ps, rs);
        }
    }

}
